/**
 * @file response 中间件
 */
import { MiddlewareFunction, RequestQuery } from "../../index.d.js"
import { getMIME } from "#utils"

/** 根据请求地址进行解析 动态设置 response.header */
export const responseHeaderMiddleware: MiddlewareFunction = (options, next) => {
  const { response, requestQuery } = options

  // 如果有后缀，根据后缀设置对应的请求解析
  const { extname } = requestQuery as RequestQuery
  const MIME = extname ? getMIME(extname.replace(/^\./, "")) : ""
  if (MIME) {
    response.setHeader("Content-Type", `${MIME};charset=utf-8`)
  } else {
    response.setHeader("Content-Type", `text/plain;charset=utf-8`)
  }

  next()
}
